﻿/*----------------------------------------------------------------
//  <copyright file="VerifyCodeService.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2024-03-04 14:44</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.AspNetCore.VerifyCode
{
    #region "验证码处理服务"
    /// <summary>
    /// 验证码处理服务
    /// </summary>
    public class VerifyCodeService : IVerifyCodeService
    {
        //常量&字段
        //private const string Separator = "#$#";
        private readonly IDistributedCache _cache;

        #region "构造函数"
        #region "初始化一个验证码处理服务的新实例"
        /// <summary>
        /// 初始化一个验证码处理服务 <see cref="VerifyCodeService"/> 的新实例
        /// </summary>
        /// <param name="cache"></param>
        public VerifyCodeService(IDistributedCache cache)
        {
            _cache = cache;
        }
        #endregion

        #endregion

        #region "方法"
        #region "校验验证码有效性"
        /// <summary>
        /// 校验验证码有效性
        /// </summary>
        /// <param name="code">要校验的验证码</param>
        /// <param name="id">验证码编号</param>
        /// <param name="removeIfSuccess">验证成功时是否移除</param>
        /// <returns></returns>
        public bool CheckCode(string code, string id, bool removeIfSuccess = true)
        {
            if (string.IsNullOrEmpty(code))
            {
                return false;
            }

            string key = $"{SettingKeyConstants.VerifyCodeKeyPrefix}_{id}";
            bool flag = code.Equals(_cache.GetString(key), StringComparison.OrdinalIgnoreCase);
            if (removeIfSuccess && flag)
            {
                _cache.Remove(key);
            }

            return flag;
        }
        #endregion
        #region "设置验证码到Session中"
        /// <summary>
        /// 设置验证码到Session中
        /// </summary>
        /// <param name="code"></param>
        /// <param name="seconds"></param>
        public string SetCode(string code, int seconds = 60 * 3)
        {
            string id = Guid.NewGuid().ToString("N");
            string key = $"{SettingKeyConstants.VerifyCodeKeyPrefix}_{id}";
            _cache.SetString(key, code, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(seconds) });
            return id;
        }
        #endregion

        #endregion

    }
    #endregion

}
